/**
 * 机器人单个技能聊天
 */
const getAccessToken = require('./getAccessToken');
const request = require('../../util/request');
const BAIDU_CHAT_HOST = 'aip.baidubce.com';
const BAIDU_CHAT_PATH = '/rpc/2.0/unit/bot/chat';

const errorInfo = (...a)=> {
    console.error(...a);
}

module.exports = (param) => {
    return new Promise((resolve,reject) => {
        getAccessToken()
            .then(token => {
                const {
                    query,
                    serviceId, //机器人id
                    botId,  //技能id
                    sessionId,  //对话上下文id
                    userId
                } = param;
                return request.ajax({
                    host : BAIDU_CHAT_HOST,
                    path : BAIDU_CHAT_PATH,
                    method : 'POST',
                    param : {
                        'access_token' : token
                    },
                    data : {
                        version : '2.0',
                        'log_id' :  `${new Date().getTime}_chair`,
                        'service_id' : serviceId,
                        request : {
                            query,
                            'user_id' : userId || 'ME',
                            'bernard_level' : 0,
                            'client_session' : '{"client_results":"", "candidate_options":[]}',
                            'updates': '',
                            'query_info' : {
                                'asr_candidates': [],
                                'type': 'TEXT',
                                'source': 'KEYBOARD'
                            }
                        },
                        bot_id : botId,
                        bot_session : "",
                        sessionId : sessionId || null,
                        sysRememberSkills : []
                    }
                });
            })
            .then(json => {
                resolve(json);
            })
            .catch(e => {
                errorInfo(`与机器人通信异常：${e}`);
                reject(e + '');
            });
    });
};